/**
 * @Title: AppContext.java
 * @Package: com.jason.fingerprint
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月18日 下午5:19:48
 * @Version: V1.0
 */
package com.jason.fingerprint;

import android.app.Application;
import android.app.Service;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Vibrator;
import android.util.Log;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.jason.fingerprint.beans.UserBean;
import com.jason.fingerprint.common.FileHelper;
import com.jason.fingerprint.common.PreferenceHelper;
import com.jason.fingerprint.common.SQLiteDatabaseHelper;
import com.jason.fingerprint.listener.MyDbUpdateListener;
import com.jason.fingerprint.listener.MyLocationListener;
import com.jason.fingerprint.utils.CommonUtils;
import com.jason.fingerprint.utils.DataUtils;
import com.tencent.bugly.crashreport.CrashReport;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.utils.StringUtils;
import org.kymjs.aframe.utils.SystemTool;

import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.finalteam.okhttpfinal.OkHttpFinal;
import cn.finalteam.okhttpfinal.OkHttpFinalConfiguration;
import okhttp3.OkHttpClient;

/**
 * @ClassName: AppContext
 * @Description: 全局应用程序类：用于保存和调用全局应用配置及访问网络数据
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月18日 下午5:19:48
 */
public class AppContext extends Application {

    private static final String TAG = "AppContext";

    public static final boolean DB_ISDEBUG = true;
    public static final String DB_NAME = "FingerPrint";
    public static final int DB_VERSION = 1;
    public static final int PAGE_SIZE = 20;// 默认分页大小

    private static final String BUGLY_APPID = "900001966";
    public static final boolean BUGLY_DEBUG = false ;  //true代表App处于调试阶段，false代表App发布阶段

    public static boolean FLAG_ONLY_ACCOUNT = false;

    /** 单例*/
    public static AppContext mInstance;
    /** 全局Context*/
    public static Context mAppContext;

    // Baidu LBS
    public LocationClient mLocationClient;
    public MyLocationListener mMyLocationListener;
    public Vibrator mVibrator;

    private KJDB kjdb;// 数据库初始化
    private UserBean userBean;// 当前的登录信息
    private SQLiteDatabase mSQLiteDatabase;

    public static AppContext getInstance(){
        return mInstance;
    }

    public static Context getAppContext(){
        if (mAppContext == null)
            mAppContext = mInstance.getApplicationContext();
        return mAppContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        mAppContext = getApplicationContext();

        //程序异常崩溃捕获
        Thread.setDefaultUncaughtExceptionHandler(new UncaughtException());
        initBaiduLBS();
        if (BUGLY_DEBUG){
            setUserBean(PreferenceHelper.getLoginInfoFormPreference(this));
        }
        initOkHttpFinal();
    }

    private void initOkHttpFinal(){
        OkHttpFinalConfiguration.Builder builder = new OkHttpFinalConfiguration.Builder()
                .setDebug(true)
                .setTimeout(60000)
                .setRetryOnConnectionFailure(true);
        OkHttpFinal.getInstance().init(builder.build());

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new LoggerInterceptor("HttpRequest"))
                .connectTimeout(180l, TimeUnit.SECONDS)
                .readTimeout(180l, TimeUnit.SECONDS)
                .build();

        OkHttpUtils.getInstance(okHttpClient);
    }

    public void initDB(){
        // 初始化数据库
        kjdb = KJDB.create(mAppContext, FileHelper.getSqlPath(mAppContext), DB_NAME,
                DB_ISDEBUG, DB_VERSION, new MyDbUpdateListener());
        mSQLiteDatabase = SQLiteDatabaseHelper.getInstance(mAppContext).openSQLiteDatabase(FileHelper.getSqlPath(mAppContext), DB_NAME);
        //SQLiteDatabaseHelper.getInstance(mAppContext).addColumn("table_dailyReport","registrationType");//日常签到添加签到类型
        //SQLiteDatabaseHelper.getInstance(mAppContext).addColumn("table_workVisit","registrationType");//工作走访添加签到类型
        //SQLiteDatabaseHelper.getInstance(mAppContext).addColumn("table_leaveout","registrationType");//外出请假添加签到类型
        //SQLiteDatabaseHelper.getInstance(mAppContext).addColumn("table_signInRecord","registrationType");//集中签到添加签到类型
        //SQLiteDatabaseHelper.getInstance(mAppContext).addColumn("table_imageAudio","registrationType");//资源添加签到类型
    }

    public void initBuglyReport(){
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(mAppContext); //App的策略Bean
        strategy.setAppChannel("慧智灵杰");     //设置渠道
        strategy.setAppVersion( getResources().getString(R.string.app_name) + "_v" + CommonUtils.getVersionName(mAppContext));      //App的版本
        strategy.setAppReportDelay(0);  //设置SDK处理延时，毫秒
        CrashReport.initCrashReport(mAppContext, BUGLY_APPID,BUGLY_DEBUG);  //初始化SDK
        CrashReport.setUserId(getImei());  //设置用户的唯一标识
    }

    private void initBaiduLBS() {
        mLocationClient = new LocationClient(this.getApplicationContext());
        mMyLocationListener = new MyLocationListener(mAppContext);
        mLocationClient.registerLocationListener(mMyLocationListener);
        mVibrator = (Vibrator) getApplicationContext().getSystemService(
                Service.VIBRATOR_SERVICE);
        initLocation();
    }

    // 初始化定位
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
        option.setScanSpan(5000);// 设置发起定位请求的间隔时间为5000ms
        option.setIsNeedAddress(true);
        option.setNeedDeviceDirect(true);// 返回的定位结果包含手机机头的方向
        mLocationClient.setLocOption(option);
    }

    /**
     * @return the kjdb
     */
    public KJDB getKjdb() {
        if (kjdb == null){
            kjdb = KJDB.create(mAppContext, FileHelper.getSqlPath(mAppContext), AppContext.DB_NAME + AppContext.getInstance().getMachId(),
                    AppContext.DB_ISDEBUG, AppContext.DB_VERSION, new MyDbUpdateListener());
        }
        return kjdb;
    }

    /**
     * @param kjdb
     *            the kjdb to set
     */
    public void setKjdb(KJDB kjdb) {
        this.kjdb = kjdb;
    }

    /**
     * @return the userBean
     */
    public UserBean getUserBean() {
        return PreferenceHelper.getLoginInfoFormPreference(this);
    }

    /**
     * @param userBean
     *            the userBean to set
     */
    public void setUserBean(UserBean userBean) {
        if (userBean == null) {
            this.userBean = PreferenceHelper.getLoginInfoFormPreference(this);
        } else {
            this.userBean = userBean;
        }
    }

    // 是否登录
    public boolean isLogin() {
        if (userBean == null){
            userBean = AppContext.getInstance().getUserBean();
        }
        return userBean != null
                && !StringUtils.isEmpty(userBean.getLoginName());
    }

    /**
     * @return the imei 当前设备的imei号码
     */
    public String getImei() {
        return SystemTool.getPhoneIMEI(this);
    }

    /**
     * @return the machId 当前登录用户的隶属机构ID
     */
    public int getMachId() {
        int machId = 0;
        if (isLogin()) {
            machId = userBean.getOrganId();
        }
        return machId;
    }

    /**
     * 当程序出现未捕获异常崩溃时调用
     */
    public void onFC(){
        Log.e(TAG, "onFC");
        int pid = android.os.Process.myPid();
        android.os.Process.killProcess(pid);
    }

    //判断是否需要同步数据
    public boolean isSynchronizedRecord(){
        String date = PreferenceHelper.getLoginDate(mAppContext);
        if (!DataUtils.getToday().equals(date)){
            return true;
        }
        return false;
    }

    //判断设备是否支持NFC
    public boolean isSupportNFC(){
//		PackageManager packageManager = getPackageManager();
//		return packageManager.hasSystemFeature(PackageManager.FEATURE_NFC);
        if (NfcAdapter.getDefaultAdapter(this) == null) {
            return false;
        }
        return true;
    }

    //获取当前设备的型号
    public String getEquipmentModel(){
        return Build.MODEL;
    }

    /***
     * 判断当前设备是否是3G设备
     * 3G:Build.MODEL="mbk82_tb_kk" || Build.MODEL="iMA122"
     * 4G:Build.MODEL="M9PLUS"
     * @return
     */
    public boolean is3GEquipment(){
        boolean flag = false;
        Log.i(TAG,"Build MODEL :" + Build.MODEL);
        if ("mbk82_tb_kk".equals(Build.MODEL)
                || "iMA122".equals(Build.MODEL)
                || "FP-05".equals(Build.MODEL)){
            flag = true;
        } else if ("M9PLUS".equals(Build.MODEL)) {
            flag = false;
        }
        Log.i(TAG,"is3GEquipment :" + flag);
        return flag;
    }

}
